package k1_jdbc.demo02.personOperation.daoImpl;

import k1_jdbc.demo02.personOperation.dao.PersonDao;
import k1_jdbc.demo02.personOperation.pojo.Person;
import k1_jdbc.tool.ConnectionTool;
import k1_jdbc.tool.Const;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class PersonDaoImplOld implements PersonDao {

    Connection conn = null;

    static{
        try {
            Class.forName(Const.DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 同时添加多个Person对象的数据
     * @param people
     * @return
     */
    @Override
    public boolean insert(List<Person> people) {

        PreparedStatement ps_insert = null;

        boolean result = true;

        try {
            conn = ConnectionTool.getDefaultConn();

            conn.setAutoCommit(false);

            ps_insert = conn.prepareStatement("insert into people values(?,?,?,?,?,?)");

            for (Person person : people) {
                ps_insert.setString(1,person.getPersonId());
                ps_insert.setString(2,person.getPersonName());
                ps_insert.setString(3,person.getDegree());
                ps_insert.setString(4,person.getBirth());
                ps_insert.setDouble(5,person.getSal());
                ps_insert.setString(6,"0");
                ps_insert.addBatch();
            }

            int[] insertCount = ps_insert.executeBatch();

            if(insertCount.length==people.size() && Arrays.stream(insertCount).allMatch(num->num==1)){
                conn.commit();
            }else{
                result = false;
                conn.rollback();
            }

        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            ConnectionTool.closed(conn,ps_insert);
        }

        return result;
    }

    @Override
    public boolean update(List<Person> people) {
        return true;
    }

    @Override
    public boolean delete(List<String> ids) {
        return true;
    }

    @Override
    public List<Person> getAll() {
        return List.of();
    }

    @Override
    public List<Person> getPersonForPage(int pagesize, int pageOrder) {
        return List.of();
    }

    @Override
    public Person getPersonById(String id) {
        return null;
    }
}
